import { HashCode } from "../components/DrawFlow/src/utils";
import { notification} from 'ant-design-vue'
/**
 * 将节点转换成后台需要的数据
 * @param {带线节点的节点list} list 
 */
export function changeData(list) {
    var newList = [];
    let qxList=[]
    for (var i in list) {
        let obj = {
            resourceId: list[i].id,
            outgoing: list[i].outgoing,
            properties: {
                overrideid: "",
                name: list[i].title,
                documentation: "",
                executionlisteners: "",
            },
            bounds: {
                lowerRight: {
                    x: 0,
                    y: 0
                },
                upperLeft: {
                    x: 0,
                    y: 0
                }
            },
            childShapes: []
        };
        
        if (list[i].type == "1") {
            obj.stencil = {
                id: "StartNoneEvent",
            };
            obj.properties.initiator = ''
            obj.properties.formkeydefinition = ""
            obj.properties.formproperties = ""

            obj.dockers = []
        } else if (list[i].type == "2") {
            let qxData
            if(list[i].data.qxData){
                for(let qx in list[i].data.qxData){
                    qxData={
                        taskDefKey:list[i].id,
                        colName: qx,
                        colPrivilege: list[i].data.qxData[qx]
                    }
                    qxList.push(qxData)
                }
            }else{

            }

            obj.stencil = {
                id: "UserTask",
            }
            obj.dockers = []
            obj.properties.asynchronousdefinition = "false"
            obj.properties.exclusivedefinition = "false"
            obj.properties.multiinstance_type = "None"
            obj.properties.multiinstance_cardinality = ""
            obj.properties.multiinstance_collection = ""
            obj.properties.multiinstance_variable = ""
            obj.properties.multiinstance_condition = ""
            obj.properties.isforcompensation = "false"
            //    指派人信息
            // obj.properties.usertaskassignment = {
            //     assignment: {
            //         candidateUsers: [],
            //         candidateGroups: [],
            //         assignee: "mftadmin"
            //     }
            // }
            let userList=[]
            let groupList=[]
            if(list[i].data.candidateUsers&&list[i].data.candidateUsers.length>0){
                for(let obj of list[i].data.candidateUsers){
                    userList.push({
                        value:obj,
                        $$hashKey : ""
                    })
                }
            }else if(list[i].data.candidateGroups1&&list[i].data.candidateGroups1.length>0){
                for(let obj of list[i].data.candidateGroups1){
                    groupList.push({
                        value:obj,
                        $$hashKey : ""
                    })
                }
            }else{
                notification.error({
                    message: '错误',
                    description:
                      '审批人未设置',
                  });
                return false
            }
            obj.properties.usertaskassignment = {
                assignment: {
                    candidateUsers: userList,
                    candidateGroups: groupList,
                    assignee: ""
                }
            }
            obj.properties.duedatedefinition = ""
            obj.properties.prioritydefinition = ""
            obj.properties.tasklisteners = ""

            obj.properties.formkeydefinition = ""
            obj.properties.formproperties = ""
        } else if (list[i].type == "4") {
            obj.stencil = {
                id: "EndNoneEvent"
            };
            obj.dockers = []
        } else if (list[i].type == "5") {

            obj.stencil = {
                id: "SequenceFlow"
            };
            obj.dockers = [{
                x: 50,
                y: 40
            }, {
                x: 14,
                y: 14
            }]
            obj.target = obj.outgoing[0]
            obj.properties.defaultflow = "false"
            obj.properties.conditionsequenceflow = ""
        }else if(list[i].type == "3"){
            obj.stencil = {
                id: "SequenceFlow"
            };
            obj.dockers = [{
                x: 50,
                y: 40
            }, {
                x: 14,
                y: 14
            }]
            obj.target = obj.outgoing[0]
            obj.properties.defaultflow = "false"
            let conditionsequenceflow=""
            if(list[i].data.mathType.key=="<>"){
                conditionsequenceflow=list[i].data.value1+"<"+list[i].data.type.key+"<"+list[i].data.value2
            }else{
                conditionsequenceflow=list[i].data.type.key+list[i].data.mathType.key+list[i].data.value1
            }
            obj.properties.conditionsequenceflow = "${"+ conditionsequenceflow+"}" 
             //条件
        }
        newList.push(obj)
    }
    return {newList,qxList}
}


/**
 * 将list数据转换成后台接收的数据
 * @param {*} list 
 */
export function getFormdata(list,obj) {
    let outgoingList=getOutgoingArr(list)
    let endList=addEnd(outgoingList)
    let lineList = addLine(endList)
    if(!changeData(lineList)){
        return false
    }
    let {newList,qxList} = changeData(lineList)
    let json_xml = {
        resourceId: obj.id,
        properties: {
            process_id: 'process'+obj.id,
            name: 'process'+obj.id,
            documentation: "",
            process_author: "",
            process_version: "",
            process_namespace: "http://www.activiti.org/processdef",
            executionlisteners: "",
            eventlisteners: "",
            signaldefinitions: "",
            messagedefinitions: ""
        },
        stencil: {
            id: "BPMNDiagram"
        },
        bounds: {
            lowerRight: {
                x: 0,
                y: 0
            },
            upperLeft: {
                x: 0,
                y: 0
            }
        },
        childShapes: newList,
        stencilset: {
            url: "stencilsets/bpmn2.0/bpmn2.0.json",
            namespace: "http://b3mn.org/stencilset/bpmn2.0#"
        },
        ssextensions: []
    }
    let formdata = {
        json_xml: JSON.stringify(json_xml),
        svg_xml: 'demo',
        name: obj.name,
        description: obj.description
    }
    formdata.jsonXml0={
        form_element_privilege:qxList,
        lc_data:{}
    }
    return formdata
}

/**
 * 添加outgoing
 * @param {*} list 
 */
export function getOutgoingArr(list){
    let map = {}; //所有整行元素的字典对象
    for (let item of list) {
        item.outgoing=[]
        map[item.id] = item;
    }
    for (let lis of list) {
        if(lis.groupId){
            if(lis.isRow){
                if(map[lis.groupId]){
                    map[lis.groupId].outgoing.push({
                        resourceId : lis.id
                    })
                }else{
                    // 节点是分支的合流(缺少合流为分支)
                    let HLid=lis.groupId
                    let outgongIdList=genColNodeNext(list,HLid)
                    for(let outgongId of outgongIdList){
                        map[outgongId].outgoing.push({
                            resourceId : lis.id
                        })
                    }

                }
            }else{
                //节点是分支节点
                if(map[lis.groupPid]){
                    map[lis.groupPid].outgoing.push({
                        resourceId : lis.id
                    })
                }
            }
        }
    }
    return list
}

/**
 * ADDoutgoing
 * @param {outgoinglist} list 
 */
 export function addEnd(list){
    let endId = HashCode()

    let newArr = list.filter( obj=> obj.type== '4');
    if(newArr.length==0){
        for(let obj of list){
            if(obj.outgoing.length==0){
                obj.outgoing.push({
                    resourceId : endId
                })
            }
        }
        let endObj={
            id: endId,
            type: "4",
            title: "结束",
            data: {},
            outgoing:[]
        }
        list.push(endObj)
    }



    return list
 }



// 添加虚拟节点
export function getColNode(list) {
    let colNodes = list.filter(i => !i.isRow);
    let map = {};
    colNodes.forEach(i => {
        if (!map[i.groupId]) {
            map[i.groupId] = [];
        }
        map[i.groupId].push(i);
    });
    let colNodesArr = [];
    for (const groupId in map) {

        let obj = {
            id: groupId,
            groupId: map[groupId][0].groupPid,
            type: "route",
            isRow: true,
            isFlowTo: map[groupId][0].type === "6",
            conditionNodes: map[groupId]
        };
        colNodesArr.push(obj);
        
    }
    list = list.concat(colNodesArr);

    return list;
}



//虚拟节点添加outgoing
export function addColNodeOutgoing(list){
    let map = {}; 
    for (let item of list) {
        map[item.id] = item;
    }
    for(let obj of list){
        if(obj.type=='route'){
            let outgoing=genColNodeNext(list,obj.id)
            map[obj.id].outgoing=outgoing
        }
    }
    return list
}

// 根据分支节点获取结束节点 id：条件节点id
export function genColNodeNext(list,id){
    let outgoing=[]
    for(let obj of list){
        if(obj.groupId==id&&!obj.isRow){
            outgoing=outgoing.concat(getEndId(list,obj.id))
        }
    }
    return outgoing
}

// 获取该条件节点下的条件节点
export function getChildRowCol(list,id){
    let map = {}; 
    for (let item of list) {
        map[item.id] = item;
    }
    let childRowCol=[]
    if(map[id].outgoing.length==0){
        
    }else{
        for(let out of map[id].outgoing){
            let col
            if(!map[out.resourceId].isRow){
                col=map[out.resourceId].groupId
            }
            childRowCol=getChildRowCol(list,out.resourceId).push(col)
        }
    }
    return childRowCol

}

// 获取节点的结束
export function getEndId(list,id){
    let map = {}; 
    for (let item of list) {
        map[item.id] = item;
    }
    let returnId=[]
    if(map[id].outgoing.length==0){
        
       returnId.push(id)
    }else{
        for(let out of map[id].outgoing){
            returnId=returnId.concat(getEndId(list,out.resourceId))
        }
    }
    return returnId

}






export function getHLlistoutgoing(list){
    let map = {}; //所有整行元素的字典对象
    for (let item of list) {
        map[item.id] = item;
    }

    for (let lis of list) {
        if(lis.groupId){
            if(lis.isRow&&!map[lis.groupId]){
                // 节点是分支的合流
                let HLid=lis.groupId
                for(let obj of list){
                    if(obj.groupId==HLid&&!obj.isRow){
                        let id
                        id= findgen(obj,list)
                        map[id].outgoing.push({
                            resourceId : lis.id
                        })
                    }
                }
            }
            if(!lis.isRow&&!map[lis.groupPid]){
                // 节点是分支的合流（合流也为分支）
                let HLid=lis.groupPid
                for(let obj of list){
                    if(obj.groupId==HLid&&!obj.isRow){
                        let id
                        id= findgen(obj,list)
                        map[id].outgoing.push({
                            resourceId : lis.id
                        })
                    }
                }
            }
        }

    }
    return list
}

// 该分支的根节点
export function findgen(obj,list){
    let map = {}; 
    for (let item of list) {
        map[item.id] = item;
    }
    if(obj.outgoing.length>0){
        for(let out of obj.outgoing){
           return findgen(map[out.resourceId],list)
        }
    }else{
        return obj.id
    }


}

/**
 * 节点list添加线节点
 * @param {节点list} list 
 */
export function addLine(list) {
    let map = {}; 
    for (let item of list) {
        map[item.id] = item;
    }
    let lineArry = []
    for (let i in list) {
        if (list[i].outgoing.length ==1&&list[i].type!="3") {
            let lineId = HashCode()
            let line = {
                id: lineId,
                groupId: list[i].id,
                type: "5",
                outgoing: list[i].outgoing
            }

            list = changeGroupId(line, list, i)

            lineArry.push(line)
        }else if(list[i].outgoing.length>1){

        }

    }
    list = list.concat(lineArry)
    // list = changeData(list)
    return list
}
/**
 * 修改子节点的groupId和父节点的outgoing
 * @param {线节点} line 
 * @param {节点list（不包含线）} list 
 * @param {当前} index 
 */
export function changeGroupId(line, list, index) {
    for (var oneLine of line.outgoing) {
        for (let j in list) {
            if (oneLine.resourceId == list[j].id) {

                list[j].groupId = oneLine.id
            }
        }
    }
    list[index].outgoing = [{
        resourceId: line.id
    }]
    return list
}


// 添加虚拟节点
export function treeDataToLine(obj) {
    let res = []
    const fn = (obj)=>{
        if(obj.childNode){
            fn(obj.childNode)
        }
        if(obj.conditionNodes){
            res.push(obj.id)
            for(let lis of obj.conditionNodes){
                fn(lis)                
            }
        }
    }
    fn(obj)
    return res
}

// 对象的扁平化处理

export function flattenF(obj) {
	var result = {};
	function process(key, value) {
		if (Object(value) !== value) {
			if (key) {
				result[key] = value;
			}
		} else if (Array.isArray(value)) {
			for (var i = 0, len = value.length; i < len; i++) {
				process(key + "[" + i + "]", value[i]);
			}
			if (value.length === 0 && key) {
				result[key] = [];
			}
		} else {
			var isEmpty = true;
			for (var prop in value) {
				isEmpty = false;
				process((key ? key + "." : key) + prop, value[prop]);
			}
			if (isEmpty && key) {
				result[key] = {};
			}
		}
	}
	process("", obj);
	return result;
}

export function treeToLine(obj,list){
    let treeList=[]
    let map = {}; 
    for (let item of list) {
        item.outgoing=[]
        map[item.id] = item;
    }
    function toList(obj,key){
        if(!obj.childNode){
            if(key!=""){
                map[key].outgoing.push(obj.id)
            }
           
        }else if(obj.childNode.type=="route"){
            if(obj.childNode.conditionNodes){
                for(let item of obj.childNode.conditionNodes){
                    if(key!=""){
                        map[key].outgoing.push(obj.id)
                    }
                    toList(item,obj.id)
                }
            }
            if(obj.childNode.childNode){
                if(key!=""){
                    map[key].outgoing.push(obj.id)
                }
                toList(obj.childNode.childNode,obj.id)
                
            }
        }else{
            if(key!=""){
                map[key].outgoing.push(obj.id)
            }
            toList(obj.childNode,obj.id)
        }
    
    }
    toList(obj[0],"")
    return map
}